<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
        >
            <el-form-item label="课程类别" prop="typeId">
                <el-select
                    v-model="queryParams.typeId"
                    placeholder="请选择"
                    :style="{ width: '100%' }"
                >
                    <el-option
                        v-for="item in typeIdOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="课程名称" prop="varName">
                <el-input
                    v-model="queryParams.varName"
                    placeholder="请输入"
                    clearable
                />
            </el-form-item>
            <el-form-item label="行业" prop="varIndustry">
                <el-select
                    v-model="queryParams.varIndustry"
                    placeholder="请选择"
                    :style="{ width: '100%' }"
                >
                    <el-option
                        v-for="item in varIndustryOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['system:course:add']"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['system:course:remove']"
                    >删除</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['system:course:export']"
                    >导出</el-button
                >
            </el-col> -->
        </el-row>

        <el-table
            v-loading="loading"
            :data="courseList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="55"
                align="center"
                :selectable="checkboxSelect"
            />
            <el-table-column label="课程类别" align="center" prop="typeId" />
            <el-table-column label="课程名称" align="center" prop="varName" />
            <el-table-column label="课程内容" align="center" prop="varDesc" />
            <el-table-column label="课程封面" align="center">
                <template slot-scope="scope">
                    <img
                        v-if="scope.row.varCoverInfo"
                        class="varCoverInfo"
                        :src="scope.row.varCoverInfo"
                        alt=""
                        srcset=""
                    />
                </template>
            </el-table-column>
            <el-table-column
                label="试题数量"
                align="center"
                prop="questionCount"
            >
            </el-table-column>
            <el-table-column label="时长" align="center">
                <template slot-scope="scope">
                    {{ scope.row.intClassHour }} 分钟
                </template>
            </el-table-column>
            <el-table-column
                label="适用行业"
                align="center"
                prop="varIndustry"
            />
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:course:edit']"
                        v-if="ancestors.length <= scope.row.intPid.length"
                        >修改</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdateAttachment(scope.row)"
                        v-hasPermi="['system:course:remove']"
                        >课件管理</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdateQuestion(scope.row)"
                        v-hasPermi="['system:course:remove']"
                        >试题管理</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:course:remove']"
                        v-if="ancestors.length <= scope.row.intPid.length"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改课程对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="700px"
            append-to-body
            :before-close="closeDialog"
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="课程名称" prop="varName">
                    <el-input
                        v-model="form.varName"
                        placeholder="请输入课程名称"
                    />
                </el-form-item>
                <el-form-item label="课程类别" prop="typeId">
                    <el-select
                        v-model="form.typeId"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in typeIdOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程内容" prop="varDesc">
                    <el-input
                        class="textarea"
                        v-model="form.varDesc"
                        type="textarea"
                        placeholder="请输入课程内容"
                    />
                </el-form-item>
                <el-form-item label="时长" prop="intClassHour">
                    <el-input
                        v-model="form.intClassHour"
                        placeholder="请输入时长"
                    >
                        <template slot="append">分钟</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="适用行业" prop="varIndustry">
                    <el-select
                        v-model="form.varIndustry"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in varIndustryOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程封面" prop="varCoverInfo">
                    <el-upload
                        class="avatar-uploader"
                        ref="upload1"
                        :limit="limitImgNumber"
                        list-type="picture-card"
                        :file-list="fileList"
                        accept=".png, .jpg"
                        :headers="upload.headers"
                        :on-remove="removeFile"
                        :action="upload.url"
                        :on-change="handleFileChange"
                        :on-success="handleFileSuccess"
                        :class="{ hideAdd: uploadDisabled }"
                    >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse, exportTemplate } from "@/api/system/course";
import { getToken } from "@/utils/auth";
export default {
    name: "Course",
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            deleteNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 课程表格数据
            courseList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload"
            },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                typeId: undefined,
                varName: undefined,
                varDesc: undefined,
                intClassHour: undefined,
                varIndustry: undefined,
            },
            limitImgNumber: 1,
            // 表单参数
            form: {
                typeId: undefined,
                varName: undefined,
                varDesc: undefined,
                intClassHour: undefined,
                varIndustry: undefined,
                varCoverInfo: undefined
            },
            // 表单校验
            rules: {
                typeId: [
                    { required: true, message: "请选择课程类别", trigger: ['blur', 'change'] }
                ],
                varName: [
                    { required: true, message: "请输入课程名称", trigger: ['blur', 'change'] }
                ],
                varDesc: [
                    { required: true, message: "请输入课程内容", trigger: ['blur', 'change'] }
                ],
                intClassHour: [
                    { required: true, message: "请输入课程", trigger: ['blur', 'change'] }
                ],
                varIndustry: [
                    { required: true, message: "请选适用行业", trigger: ['blur', 'change'] }
                ]
            },
            fileList: [],
            uploadDisabled: false,
            typeIdOptions: [], // 课程类别
            varIndustryOptions: [], // 适用行业
            chrCategoryOptions: [], // 试题类型
            ancestors: ''
        };
    },
    created () {
        this.getList();
        this.getDicts("type_id").then(response => {
            this.typeIdOptions = response.data;
        });
        this.getDicts("var_industry").then(response => {
            this.varIndustryOptions = response.data;
        });

        this.getDicts("chr_category").then(response => {
            this.chrCategoryOptions = response.data;
        });
    },
    methods: {
        checkboxSelect (row) {
            return this.ancestors.length <= row.intPid.length
        },
        closeDialog (done) {
            this.$refs.upload1.clearFiles()
            done()
        },
        removeFile (file, fileList) {
            this.form.varCoverInfo = ''
            this.handleFileChange(file, fileList)
        },
        handleFileChange (file, fileList) {
            this.uploadDisabled = fileList.length >= this.limitImgNumber;
        },
        handleFileSuccess (res) {
            this.form.varCoverInfo = res.url
        },
        dataFormat (val, options) {
            for (let i = 0; i < this[options].length; i++) {
                if (val == this[options][i].dictLabel) {
                    return this[options][i].dictValue
                }
            }
            return val
        },
        /** 查询课程列表 */
        getList () {
            this.loading = true;
            listCourse(this.queryParams).then(response => {
                this.courseList = response.data.rows;
                this.ancestors = response.data.ancestors;

                response.data.rows.forEach(item => {
                    if (item.photos[0] != null) {
                        item.varCoverInfo = item.photos[0].attaPath;
                    }

                });
                this.total = response.data.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.$refs.upload1.clearFiles()
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                typeId: undefined,
                varName: undefined,
                varDesc: undefined,
                intClassHour: undefined,
                varIndustry: undefined,
                varCoverInfo: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id)
            this.deleteNames = selection.map(item => item.varName)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.open = true;
            this.uploadDisabled = false
            this.title = "添加课程";
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const id = row.id || this.ids
            getCourse(id).then(response => {
                for (const key in this.form) {
                    this.form[key] = response.data[key]
                }
                if (response.data.photos[0] != null) {
                    this.form.varCoverInfo = response.data.photos[0].attaPath;
                }
                this.fileList = this.form.varCoverInfo ? [{ url: this.form.varCoverInfo }] : []
                this.uploadDisabled = this.fileList.length >= this.limitImgNumber;
                this.form.id = response.data.id
                this.open = true;
                this.title = "修改课程";
            });
        },
        /** 课件按钮操作 */
        handleUpdateAttachment (row) {
            this.$router.push({
                path: '/resourse/coursrAttachment',
                query: {
                    courseId: row.id,
                    jurisdiction: this.ancestors.length <= row.intPid.length
                }
            })
        },
        /** 试题按钮操作 */
        handleUpdateQuestion (row) {
            this.$router.push({
                path: '/resourse/courseQuestion',
                query: {
                    courseId: row.id,
                    jurisdiction: this.ancestors.length <= row.intPid.length
                }
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        this.form.typeId = this.dataFormat(this.form.typeId, 'typeIdOptions')
                        this.form.varIndustry = this.dataFormat(this.form.varIndustry, 'varIndustryOptions')
                        this.form.chrCategory = this.dataFormat(this.form.chrCategory, 'chrCategoryOptions')
                        updateCourse(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.restoreState()
                            }
                        });
                    } else {
                        addCourse(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.restoreState()
                            }
                        });
                    }
                }
            });
        },
        restoreState () {
            this.$refs.upload1.clearFiles()
            this.uploadDisabled = false
            this.open = false;
            this.getList();
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const ids = row.id || this.ids;
            const names = row.varName || this.deleteNames.join('，')
            this.$confirm('是否确认删除课程名称为"' + names + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delCourse(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () { });
        },
        /** 导出按钮操作 */
        // handleExport () {
        //     const queryParams = this.queryParams;
        //     this.$confirm('是否确认导出所有课程数据项?', "警告", {
        //         confirmButtonText: "确定",
        //         cancelButtonText: "取消",
        //         type: "warning"
        //     }).then(function () {
        //         return exportCourse(queryParams);
        //     }).then(response => {
        //         this.download(response.msg);
        //     }).catch(function () { });
        // },
    }
};
</script>
<style scoped>
.varCoverInfo {
    max-width: 100px;
    max-height: 100px;
}
.textarea >>> textarea {
    height: 120px;
}
</style>
